import java.net.*;
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;
import java.security.interfaces.*;
import java.math.*;
public class ServerReceive{
    public static void main(String []args) throws Exception
    {
        ServerSocket sc = null;
        Socket socket=null;
        try
        {
            MyDC evaluator = new MyDC();

            sc= new ServerSocket(50);//创建服务器套接字
            //System.out.println("端口号:" + sc.getLocalPort());
            System.out.println("服务器成功启动，等待客户端应答");
            socket = sc.accept();   //等待客户端连接
            System.out.println("已经建立连接");//获得网络输入流对象的引用
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));//获得网络输出流对象的引用
            PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
            //使用服务器端RSA的私钥对DES的密钥进行解密
            String aline2=in.readLine();
            System.out.println("客户端发来的信息为："+aline2);


            // 获取密钥
            byte[]ctext=aline2.getBytes("ISO-8859-1");
            // 读取对方的DH公钥
            FileInputStream f1=new FileInputStream("Bpub");
            ObjectInputStream b1=new ObjectInputStream(f1);
            PublicKey  pbk=(PublicKey)b1.readObject( );
            //读取自己的DH私钥
            FileInputStream f2=new FileInputStream("Asec");
            ObjectInputStream b2=new ObjectInputStream(f2);
            PrivateKey  prk=(PrivateKey)b2.readObject( );
            // 执行密钥协定
            KeyAgreement ka=KeyAgreement.getInstance("DH");
            ka.init(prk);
            ka.doPhase(pbk,true);
            //生成共享信息
            byte[ ] sb=ka.generateSecret();
            byte[]ssb=new byte[24];
            for(int i=0;i<24;i++)
                ssb[i]=sb[i];
            SecretKeySpec k=new  SecretKeySpec(ssb,"DESede");

            // 解密
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            byte []ptext=cp.doFinal(ctext);
            // 显示明文
            String p=new String(ptext,"UTF8");
            int ans = evaluator.evaluate(p);
            out.println(ans);
            System.out.println("Result = "+ans);

        } catch (Exception e) {
            System.out.println(e);
        }
    }

    //十六进制和十进制转换
    public static byte[] parseHexStr2Byte(String hexStr)
    {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++)
        {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1 ), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}

